package com.example;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class BeanUtilsDemo {

    // 使用BeanUtils框架操作属性
    @Test
    public void test1() throws Exception {
        Student student = new Student();
        String name = BeanUtils.getProperty(student, "name");
        System.out.println(name);

        BeanUtils.setProperty(student, "name", "Alice");
        System.out.println(student.getName());
    }

    @Test
    public void test2() throws Exception {
        Student student = new Student();
        String age = BeanUtils.getProperty(student, "age");
        System.out.println(age);

        BeanUtils.setProperty(student, "age", "50");
        System.out.println(student.getAge());
    }

    @Test
    public void test3() throws Exception {
        Student student = new Student();
        String birthday = BeanUtils.getProperty(student, "birthday");
        System.out.println(birthday);

        // 注册转换器
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        BeanUtils.setProperty(student, "birthday", "1989-10-09");
        System.out.println(student.getBirthday());
    }

    @Test
    public void test4() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Steve");
        map.put("age", 39);
        map.put("birthday", "1989-10-09");

        Student student = new Student();
        System.out.println("before populate:" + student);
        // 注册转换器
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        BeanUtils.populate(student, map);
        System.out.println("after populate:" + student);
    }

}
